import pandas as pd
import os
import time
import warnings
import numpy as np
from sklearn.cluster import KMeans


warnings.filterwarnings('ignore')

def report(folder_path, gt, pred, raw_pred, test_energy):
    # 对于large SSD统计预测的提前量 
    result = pd.DataFrame({"gt":gt, "preds":raw_pred})
    statistics_lookahead(result)
    
    from sklearn import metrics
    print(f" Classification report for classifier \n %s\n"
        % ( metrics.classification_report(gt, pred, digits=4)))
    print("Confusion matrix:\n%s" % metrics.confusion_matrix(gt, pred))
    
    # gt = gt[:, np.newaxis].astype(int)
    # pred = pred[:, np.newaxis].astype(int)
    # raw_pred = raw_pred[:, np.newaxis].astype(int)
    # test_energy = test_energy[:, np.newaxis]
    # np.savetxt(os.path.join(folder_path, "result.csv"), np.concatenate([gt, pred, raw_pred, test_energy], axis=1), 
    #             delimiter=",",header="gt,pred,raw_pred,energy" ) 


def statistics_lookahead(data):
    seg_pos = data["gt"].diff()
    begin = seg_pos[seg_pos==1].index.tolist()
    end = seg_pos[seg_pos==-1].index.tolist()
    if len(end) < len(begin):
        end.append(len(data)) # 以1为gt的最后一个标注时
    assert len(begin) == len(end), "区段起止位置无法配对"
    
    hit_rows = data[(data["preds"]==1) & (data["gt"]==1)].index.tolist()
    
    print("\n所有命中点的提前量直方图:")
    lookahead = []
    for row in hit_rows:
        for s, e in zip(begin, end):
            if  s <= row <= e:
                lookahead.append(data.loc[row:e, "gt"].sum())
    
    # 生成文字形式的直方图
    hist = text_histogram(lookahead)
    print(hist)
    
    print("\n区段最早命中点的提前量直方图:")
    lookahead = []
    for s, e in zip(begin, end):
        for row in hit_rows:
            if  s <= row <= e:
                lookahead.append(data.loc[row:e, "gt"].sum())
                break
    hist = text_histogram(lookahead)
    print(hist)
    return

def text_histogram(data, bins=9, bar_char="*"):
    """
    根据输入数据生成文字形式的直方图。

    :param data: 输入的一维数据，通常是 Pandas Series
    :param bins: 分箱的数量，默认为 5
    :param bar_char: 用于绘制直方图的字符，默认为 '*'
    :return: 文字形式的直方图字符串
    """
    hist, bin_edges = np.histogram(data, range=(0, 180), bins=bins)
    hist_str = ""
    for i in range(bins):
        bin_range = f"[{bin_edges[i]:.1f}, {bin_edges[i + 1]:.1f})"
        bar = hist[i]
        bar_str = len(str(bar)) * bar_char
        hist_str += f"{bin_range}: {bar} {bar_str}\n"
    return hist_str